package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishDisableFailedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.mapper.SetMealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetMealDishMapper setMealDishMapper;
    @Autowired
    private SetMealMapper setMealMapper;
    /**
     * 新增菜品和口味
     * @param dishDTO
     */
    @Transactional//开启事务注解 因为对两张表修改了 原子性
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //插入一条菜品
        dishMapper.insert(dish);
        //主键返回了
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0){
            //设置dishId
            flavors.forEach(flavor -> flavor.setDishId(dishId));
        }
        //批量插入
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //pageHelper写limit 自己否则写正常查询语句
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        long total = page.getTotal();
        List<DishVO> records = page.getResult();
        return new PageResult(total,records);
    }

    /**
     * 菜品批量删除
     * @param ids
     */
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //先写业务逻辑 再写代码
        //1.判断是否可以删除
        //1.1是否是起售状态 起售不可删
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //1.2是否和套餐管理 管理不可删 能查出来套餐id就说明有菜品是和套餐关联的
        List<Long> setMealIds = setMealDishMapper.getSetMealIdsByDishIds(ids);
        if(setMealIds != null && setMealIds.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //2.可以删除
        //2.1删除菜品表
//        for (Long id : ids) {
//            dishMapper.deleteById(id);
//            //2.2删除菜品对应的口味表
//            dishFlavorMapper.deleteByDishId(id);
//        }
        //批量删除菜品
        dishMapper.deleteByIds(ids);
        //批量删除菜品对应的口味
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 根据id查询菜品和对应的口味
     * @param id
     * @return
     */
    public DishVO getByIdWithFlavor(Long id) {
        //根据id查询菜品
        Dish dish = dishMapper.getById(id);
        //根据菜品查询口味
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        //封装到vo返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 根据id修改菜品的基本信息和对应的口味信息
     * @param dishDTO
     */
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        //修改菜品表的基本信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        //删除原先的口味表信息 为了统一追加操作和更新操作 统一删除 后添加
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //重新添加口味信息 多表之间的操作 添加要看是否有外键id赋值
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //判断是否有口味 和给口味赋值dishId
        if(flavors != null && flavors.size() > 0){
            flavors.forEach(flavor->flavor.setDishId(dishDTO.getId()));
        }
        if (flavors != null && flavors.size() > 0)
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     *根据分类查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getDishByCategory(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();//只能查询到起售的菜品才能加入到套餐里面
        List<Dish> dishes = dishMapper.getDishByCategory(dish);
        return dishes;
    }

    /**
     * 启用禁用菜品
     * @param status
     * @param id
     */
    public void startOrStop(Integer status, Long id) {
        //如果套餐是启用的 就不能禁用菜品
        if(status == StatusConstant.DISABLE){
            List<Setmeal> setmeals = setMealMapper.getByDish(id);
            if(setmeals != null && setmeals.size() > 0){
                setmeals.forEach(setmeal -> {if(setmeal.getStatus() == StatusConstant.ENABLE)
                    throw new DishDisableFailedException(MessageConstant.DISH_DISABLE_FAILED);
                });
            }
        }
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);
    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getDishByCategory(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
